package com.wjh.BeanPostProcessor;
import com.wjh.anno.HAutowired;
import com.wjh.anno.HComponent;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@HComponent
public class DIBeanPostProcessor implements BeanPostProcessor{
    @Override
    public Object postProcessBeforeInitialization(Set<Class> classSet, Map<Class<?>,Object>beanMap) {
        for(Class<?> clazz:classSet){
        Field[] fields = clazz.getDeclaredFields();
        if(fields == null) continue;
        for(Field field :fields){
            //如果有该注解，则进行注入对象实例
            if(field.isAnnotationPresent(HAutowired.class)) {
                //1.先获取类型
                Class<?> fieldType = field.getType();
                //2.从IOC容器中查找有对应的bean或者子类或实现类
                Object fieldBean = beanMap.get(fieldType);
                if (fieldBean == null) {
                    Set<Class<?>> resultSet = getClassesBySuperOrInterface(fieldType,classSet );
                    fieldBean = resultSet.iterator().next();//把其中一个注入就行
                    //进行赋值
                    field.setAccessible(true);
                    try {
                        field.set(beanMap.get(clazz), beanMap.get(fieldBean));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
            }
        }
        return null;
    }

    private Set<Class<?>> getClassesBySuperOrInterface(Class<?> fieldType,Set<Class> list) {
        Set<Class<?>> classSet = new HashSet<>();
        for(Class<?> clazz :list){
            //判断是不是子类或者实现类
            if (fieldType.isAssignableFrom(clazz) && !clazz.equals(fieldType)){
                classSet.add(clazz);
            }
        }
        return classSet;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        return null;
    }
}
